package com.lanou3g.ptp.grade.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.lanou3g.ptp.entity.*;
import com.lanou3g.ptp.grade.mapper.GradeMapper;
import com.lanou3g.ptp.grade.mapper.GradeRoleMapper;
import com.lanou3g.ptp.grade.mapper.GradeTeacherMapper;
import com.lanou3g.ptp.grade.service.GradeService;
import com.lanou3g.ptp.task.service.TaskService;
import com.lanou3g.ptp.taskrole.service.TaskRoleService;
import com.lanou3g.ptp.taskstudent.service.TaskStudentService;
import com.lanou3g.ptp.vo.MyGradesParam;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service(timeout = 10000)
public class GradeServiceImpl implements GradeService {
    @Autowired
    private GradeMapper gradeMapper;
    @Autowired
    private GradeTeacherMapper gradeTeacherMapper;
    @Autowired
    private GradeRoleMapper gradeRoleMapper;
    @Reference
    private TaskService taskService;
    @Reference
    private TaskRoleService taskRoleService;
    @Reference
    private TaskStudentService taskStudentService;

    //  添加一个grade
    @Override
    public void insertGrade(Grade grade) {
        grade.setCreateTime(new Date());
        grade.setUpdateTime(new Date());
        gradeMapper.insertGrade(grade);
    }

    //  更改grade信息
    @Override
    public void updateGrade(Grade grade) {
        grade.setUpdateTime(new Date());
        gradeMapper.updateGrade(grade);
    }

    //  查找全部grade
    @Override
    public List<Grade> findAll() {
        List<Grade> gradeList = gradeMapper.findAll();
        return gradeList;
    }

    //  根据id查找grade
    @Override
    public Grade findById(Long id) {
        Grade grade = gradeMapper.findById(id);
        return grade;
    }

    //  通过id删除grade
    @Override
    public void deleteById(Long id) {
        gradeMapper.deleteById(id);
    }

    //  通过id删除grade
    @Override
    public void deleteGradeRoleById(Long gradeId) {
        gradeMapper.deleteGradeRoleById(gradeId);
    }

    //  通过ids批量查询
    @Override
    public void deleteByIds(Integer[] ids) {
        gradeMapper.deleteByIds(ids);
    }

    //    通过taskId查询所有参与这次打分的老师
    @Override
    public List<Long> findByTaskId(Long taskId) {
        List<Long> roleIds = new ArrayList<>();
        List<TaskRole> taskRoles = gradeMapper.findByTaskId(taskId);
        for (TaskRole taskRole : taskRoles) {
            roleIds.add(taskRole.getId());
        }
        return roleIds;
    }

    @Override
    public int addGradeTeacher(GradeTeacher gradeTeacher) {
        int i = gradeTeacherMapper.insert(gradeTeacher);
        if (i > 0) {
            Long taskId = gradeTeacher.getTaskId();
            List<GradeTeacher> gradeTeachers = gradeTeacherMapper.findByTaskId(taskId);
            List<Student> students = taskStudentService.findStudentsByTaskId(taskId);
            int gradeTeacherSize = gradeTeachers.size();
            if (gradeTeacherSize == students.size()) {
                int evaluate = 0;
                for (GradeTeacher gt : gradeTeachers) {
                    evaluate += gt.getScore();
                }
                evaluate = evaluate / gradeTeacherSize;
                taskService.updateEvaluate(taskId, evaluate);
            }
            return i;
        }
        return 0;
    }

    @Override
    public GradeTeacher findGradeTeacherByStudentIdAndTaskId(Long studentId, Long taskId) {
        return gradeTeacherMapper.findByStudentIdAndTaskId(studentId, taskId);
    }

    @Override
    public boolean postGrade(Teacher teacher, GradeItem gradeItem) {
        // 查询该学生的总成绩信息是否存在，没有则创建
        Long studentId = gradeItem.getStudentId();
        Long taskId = gradeItem.getTaskId();
        Grade grade = gradeMapper.findByTaskIdAndStudentId(taskId, studentId);
        if (grade == null) {
            grade = initGrade(studentId, taskId);
        }
        // 检查打分资格
        Long gradeId = grade.getId();
        GradeRole gradeRole = getGradeRole(teacher.getId(), taskId, gradeId);
        if (gradeRole != null && gradeRole.getScore() == null) {
            int score = calScore(gradeItem);
            gradeRole.setScore(score);
            gradeRole.setEvaluate(gradeItem.getRemark());
            gradeRole.setStatus(0);
            Date now = new Date();
            gradeRole.setCreateTime(now);
            gradeRole.setUpdateTime(now);
            int i = gradeRoleMapper.addGradeRole(gradeRole);
            // 处理学生该任务的总分
            handleFinalGrade(taskId, gradeId);
            return i > 0;
        } else {
            return false;
        }
    }

    @Override
    public MyGrades getMyGrades(MyGradesParam myGradesParam, Long teacherId, Long studentId) {
        if (teacherId != null) {
            return getTeacherGrades(myGradesParam.getTaskId(), teacherId, myGradesParam.getStudentId());
        }
        if (studentId != null) {
            return getStudentGrades(myGradesParam.getTaskId(), studentId);
        }
        return null;
    }

    private MyGrades getStudentGrades(Long taskId, Long studentId) {
        MyGrades myGrades = new MyGrades();
        GradeTeacher gradeTeacher = gradeTeacherMapper.findByStudentIdAndTaskId(studentId, taskId);
        if (gradeTeacher != null && gradeTeacher.getScore() != null) {
            myGrades.setEvaluate(gradeTeacher.getScore());
        } else {
            return myGrades;
        }
        Grade grade = gradeMapper.findByTaskIdAndStudentId(taskId, studentId);
        if (grade != null && grade.getScore() != null) {
            myGrades.setGrade(grade.getScore());
        }
        return myGrades;
    }

    private MyGrades getTeacherGrades(Long taskId, Long teacherId, Long studentId) {
        MyGrades myGrades = new MyGrades();
        if (studentId != null) {
            GradeRole gradeRole = gradeRoleMapper.findByTaskIdAndTeacherIdAndStudentId(taskId, teacherId, studentId);
            if (gradeRole != null && gradeRole.getScore() != null) {
                myGrades.setGrade(gradeRole.getScore().doubleValue());
            }
            return myGrades;
        }
        List<GradeRole> gradeRoles = gradeRoleMapper.findByTaskIdAndTeacherId(taskId, teacherId);
        if (gradeRoles.size() > 0 && gradeRoles.get(0).getRoleId().equals(Role.ROLE_BASE_TEACHER)) {
            List<Student> students = taskStudentService.findStudentsByTaskId(taskId);
            if (gradeRoles.size() == students.size()) {
                Integer finalEvaluate = getFinalEvaluate(taskId);
                myGrades.setEvaluate(finalEvaluate);
            }
        }
        return myGrades;
    }

    @Override
    public Integer getFinalEvaluate(Long taskId) {
        return taskService.findById(taskId).getEvaluate();
    }

    private void handleFinalGrade(Long taskId, Long gradeId) {
        ArrayList<TaskRole> taskRoles = taskRoleService.findByTaskId(taskId);
        List<GradeRole> gradeRoles = gradeRoleMapper.findByGradeId(gradeId);
        // 所有教师评分结束，开始计算总分
        if (gradeRoles.size() == taskRoles.size()) {
            gradeRoles.sort((o1, o2) -> (int) (o2.getRoleId() - o1.getRoleId()));
            taskRoles.sort((o1, o2) -> (int) (o2.getRoleId() - o1.getRoleId()));
            double score = 0.0;
            for (int i = 0; i < taskRoles.size(); i++) {
                TaskRole taskRole = taskRoles.get(i);
                GradeRole gradeRole = gradeRoles.get(i);
                score += gradeRole.getScore() * taskRole.getRatio();
            }
            Grade grade = new Grade();
            grade.setId(gradeId);
            grade.setScore(score);
            grade.setUpdateTime(new Date());
            gradeMapper.updateGrade(grade);
        }
    }

    private int calScore(GradeItem gradeItem) {
        List<TaskGradeItem> taskGradeItems = taskService.getTaskGradeItemsByTaskId(gradeItem.getTaskId());
        List<Grades> grades = gradeItem.getGrades();
        int score = 0;
        for (int i = 0; i < grades.size(); i++) {
            Grades grade = grades.get(i);
            TaskGradeItem taskGradeItem = taskGradeItems.get(i);
            Double ratio = taskGradeItem.getRatio();
            score += (int) Math.round(grade.getScore() * ratio);
        }
        return score;
    }

    private GradeRole getGradeRole(Long teacherId, Long taskId, Long gradeId) {
        Task task = taskService.findById(taskId);
        Long schoolTeacherId = task.getTeacherId1();
        Long baseTeacherId = task.getBaseTeacherId();
        if (teacherId == null) {
            return null;
        }
        long roleId;
        if (teacherId.equals(schoolTeacherId)) {
            roleId = Role.ROLE_SCHOOL_TEACHER;
        } else if (teacherId.equals(baseTeacherId)) {
            roleId = Role.ROLE_BASE_TEACHER;
        } else {
            return null;
        }
        // 查询当前教师对该学生是否打过分
        GradeRole gradeRole = gradeRoleMapper.findByGradeIdAndRoleId(gradeId, roleId);
        if (gradeRole == null) {
            gradeRole = new GradeRole();
            gradeRole.setGradeId(gradeId);
            gradeRole.setRoleId(roleId);
        }
        return gradeRole;
    }

    private Grade initGrade(Long studentId, Long taskId) {
        Grade grade = new Grade();
        grade.setStudentId(studentId);
        grade.setTaskId(taskId);
        grade.setStatus(0);
        Date now = new Date();
        grade.setCreateTime(now);
        grade.setUpdateTime(now);
        gradeMapper.insertGrade(grade);
        return grade;
    }

}
